#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
import urllib
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
import urlparse
import logging
from esr_parser.core import get_item_id
from esr_parser.utils import func
logger = logging.getLogger(__name__)


class Order(object):
    general = ''
    popular = '_deal'
    sales = '_credit'
    pricing_asc = 'price'
    pricing_desc = '_price'


class Rank_Task(object):
    driver = None

    def __init__(self, driver, keyword, order_by=Order.general, tm_only=False, limit=200):
        self.driver = driver
        self.keyword = keyword
        self.limit = limit
        self.start_driver()
        self.order_by = order_by
        self.tm_only = tm_only

    @func.auto_retry(3)
    def process(self):
        keyword = self.keyword
        result_items = []
        result_right_items = []
        result_bottom_items = []
        retry = 0
        self.search_items()
        while self.current_item_size() < self.limit:
            self.next_page()
        items = self.parse_page()

        return items

    search_page = 'http://m.intl.taobao.com/search/search.html?q={}'

    @func.auto_retry(3)
    def search_items(self):
        logger.debug('start search items')

        page_url = self.search_page.format(
            urllib.quote_plus(self.keyword.encode('utf-8')))
        self.driver.get(page_url)
        pass

    def current_item_size(self):
        return len(self.driver.find_elements_by_css_selector('.list-item'))

    def next_page(self):
        driver = self.driver
        foot_elem = driver.find_element_by_css_selector('.search-loading')

        page_size = 10
        current = self.current_item_size()
        if not current or current % page_size:
            return

        actions = ActionChains(driver)
        actions.move_to_element(foot_elem)
        actions.perform()

        WebDriverWait(self.driver, 5).until(
            lambda x: self.current_item_size() > current)

    @func.auto_retry(3)
    def parse_page(self, meta={}):
        logger.debug('parse page')
        driver = self.driver
        items = driver.find_elements_by_css_selector('.list-item')

        items = self.parse_items(items)
        return items

    @func.auto_retry(3)
    def parse_items(self, items, meta={}):
        result = []
        for index, item in enumerate(items):
            item_info = {}
            item_info['is_tm'] = None
            item_info['page_set'] = index
            item_info['page_num'] = 1
            item_info['pro_name'] = item.find_element_by_css_selector(
                '.d-title').text
            paid_elem = item.find_elements_by_css_selector('.d-num')
            item_info['month_pays'] = paid_elem and paid_elem[0].text or None
            item_info['price'] = item.find_element_by_css_selector(
                '.d-price').text
            item_info['pro_url'] = item.find_element_by_css_selector(
                '.p a').get_attribute('href')
            urlinfo = urlparse.urlparse(item_info['pro_url'])
            params = dict(urlparse.parse_qs(urlinfo.query))
            item_info['pro_img_url'] = item.find_element_by_css_selector(
                '.p-pic').get_attribute('src')

            try:
                item_info['auction_num_id'] = get_item_id(item_info['pro_url'])
            except:
                item_info['auction_num_id'] = None

            item_info.update(meta)

            result.append(item_info)
        return result
